package Client;

import java.awt.EventQueue;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JFrame;

import comunicationFrames.LoginRequest;
import comunicationFrames.LoginResponse;
import comunicationFrames.Message;

public class ComunicatorClient {
	private static final int LOGIN_PORT = 3000;  
	private static final int MESSAGE_PORT = 3001;  
	public static final int SEARCH_PORT = 3002;
	
	private Thread messageListener;
	private ObjectInputStream socketReader;
	private ObjectOutputStream socketWriter;
	private ObjectOutputStream messageWriter;
	private String serverIp;
	private long number;
	private String username;
	private char[] password;
	private String name;
	private boolean loggedIn;
	private ContactsManager manager = new ContactsManager();
	private List<ConversationFrame> activeTalks;
	
	public ComunicatorClient() {
		super();
		this.serverIp = "127.0.0.1";
		this.activeTalks = new LinkedList<ConversationFrame>();
	}
	
	public void sendMessage(Message m) {
		try {
			Socket s = new Socket(serverIp, MESSAGE_PORT);
			messageWriter = new ObjectOutputStream(s.getOutputStream());
			messageWriter.writeObject(m);
			messageWriter.flush();
			messageWriter.close();
		} catch (UnknownHostException e) {
			System.err
					.println("Error connectiong to message socket:" +
							"unknown host at " + serverIp);
		} catch (IOException e) {
			System.err.println("Error setting up socket connection: " + e);
		}
	}
	
	public LoginResponse login() {
		try {
			Socket client = new Socket(serverIp, LOGIN_PORT);
			socketReader = new ObjectInputStream(client.getInputStream());
			socketWriter = new ObjectOutputStream(client.getOutputStream());
			Object response;
			LoginResponse serverAnswer;
			//Trying to log in
			LoginRequest request = new LoginRequest(username, password);
			socketWriter.writeObject(request);
			//Receiving an answer
			response = socketReader.readObject();
			if (response instanceof LoginResponse) {
				serverAnswer = (LoginResponse) response;
				if(serverAnswer.getStatus() != 1) {
					return serverAnswer;
				}
				number = Long.valueOf(serverAnswer.getMessage());
				name = username;
				messageListener = new Thread(new MessageListener()); 
				messageListener.start();
				loggedIn = true;
				return serverAnswer;
			} else {					
				return new LoginResponse(-1, "Unknown server response.");
			}
		} catch (UnknownHostException e) {
			System.err
					.println("Error setting up socket connection: unknown host at ");
		} catch (IOException e) {
			System.err.println("Error setting up socket connection: " + e);
		} catch (ClassNotFoundException e) {
			System.err.println("Error reading object from stream: " + e);
		}
		assert false;
		return new LoginResponse(-1, "Error during logging.");
	}
	
	/*
	 * Checks if conversation with given number already started.
	 * If not, creates new frame for conversation.
	 */
	public ConversationFrame activateConversation(long with) {
		ConversationFrame result = null;
		for (ConversationFrame frame : activeTalks) {
			if (with == frame.getInterlocutorNumber()) {
				result = frame;
			}
		}
		if (result == null) {
			result = 
					new ConversationFrame(ComunicatorClient.this,
										  with);
			activeTalks.add(result);
		}
		return result;
	}
	
	public void tearDownConnection() {
		try {
			if (socketWriter != null) {
				socketWriter.close();
			}
			if (socketReader != null) {
				socketReader.close();
			}
		} catch (IOException e) {
			System.out.println("Error tearing down socket connection: " + e);
		}
	}

	public String getServerIp() {
		return serverIp;
	}
	
	public String getName() {
		return name;
	}
	
	public long getNumber() {
		return number;
	}
	
	public ContactsManager getContactsManager() {
		return manager;
	}
	
	public boolean isLogged() {
		return loggedIn;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public void setPassword(char[] password) {
		this.password = password;
	}
	
	public void setServerIp(String serverIp) {
		this.serverIp = serverIp;
	}

	@Override
	protected void finalize() throws Throwable {
		tearDownConnection();
		super.finalize();
	}

	private class MessageListener implements Runnable {
		@Override
		public void run() {
			try {
				Message m;
				while(loggedIn) {
					Object o = socketReader.readObject();
					if (o instanceof Message) {
						m = (Message) o;
						long sender = m.getFrom();
						ConversationFrame activeConversation =
								activateConversation(sender);
						activeConversation.setVisible(true);
						activeConversation.setState(JFrame.NORMAL);
						activeConversation.displayMessage(m);
					}	
				}
			} catch (IOException e) {
				if (e.getMessage().equals("socket closed")) {
					// Nothing wrong, ignore the exception
				} else {
					System.out.println("MessageListener: Couldn't read message: " + e);
					e.printStackTrace();
				}
			} catch (ClassNotFoundException e) {
				System.out.println("MessageListener: Couldn't read message: " + e);
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					LoginFrame frame = new LoginFrame(new ComunicatorClient());
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});	
	}
}